<template>
  <div>
    <!-- 页面标题栏 -->
    <div class="page-header" style="margin-bottom: 20px;">
      <h2 style="color: #409EFF; font-size: 20px; margin-bottom: 0;">种类管理</h2>
    </div>
    
    <!-- 搜索和添加按钮区域 -->
    <div class="flex items-center mb-4">
      <el-input 
        v-model="searchName" 
        placeholder="请输入种类名称" 
        @keyup.enter="fetchCategories" 
        class="flex-1 mr-4 custom-input" 
        size="default"
        :prefix-icon="Search"
      />
      <el-button 
        type="primary" 
        @click="addDialogVisible = true"
        size="default"
        :icon="Plus"
      >
        添加种类
      </el-button>
    </div>
    
    <!-- 种类表格 -->
    <el-card shadow="hover" class="mb-6" style="border-radius: 4px;">
      <el-table 
        :data="categories" 
        stripe 
        border="false"
        style="width: 100%"
        v-loading="loading"
        element-loading-text="加载中..."
        header-row-class-name="table-header"
        class="custom-table"
      >
        <el-table-column prop="categoryName" label="种类名称" align="center" min-width="180" />
        <el-table-column prop="sortLevel" label="排序等级" align="center" min-width="120" />
        <el-table-column label="操作" align="center" min-width="180" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="editCategory(scope.row)"
              :icon="Edit"
              class="mr-2"
            >
              修改
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="showDeleteConfirm(scope.row.categoryId)"
              :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
        class="custom-pagination"
      />
    </div>

    <!-- 添加种类对话框 -->
    <el-dialog 
      v-model="addDialogVisible" 
      title="添加种类"
      width="500px"
      center
    >
      <el-form :model="addForm" label-width="80px" ref="addFormRef" :rules="rules">
        <el-form-item label="种类名称" prop="categoryName">
          <el-input v-model="addForm.categoryName" placeholder="请输入种类名称" />
        </el-form-item>
        <el-form-item label="排序等级" prop="sortLevel">
          <el-input v-model.number="addForm.sortLevel" placeholder="请输入排序等级" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseAddDialog">取消</el-button>
          <el-button type="primary" @click="showAddConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改种类对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="修改种类"
      width="500px"
      center
    >
      <el-form ref="editFormRef" :model="editForm" label-width="80px" :rules="rules">
        <el-form-item label="种类名称" prop="categoryName">
          <el-input v-model="editForm.categoryName" placeholder="请输入种类名称" />
        </el-form-item>
        <el-form-item label="排序等级" prop="sortLevel">
          <el-input v-model.number="editForm.sortLevel" placeholder="请输入排序等级" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseEditDialog">取消</el-button>
          <el-button type="primary" @click="showUpdateConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive} from 'vue';
import axiosInstance from '../axiosInstance';
import {ElMessageBox} from 'element-plus';
import {Search, Plus, Edit, Delete} from '@element-plus/icons-vue';

const searchName = ref('');
const categories = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const loading = ref(false);
const addForm = ref({
  categoryName: '',
  sortLevel: 0
});
const editForm = ref({
  categoryName: '',
  sortLevel: 0
});
const addFormRef = ref(null);
const editFormRef = ref(null);

// 表单验证规则
const rules = reactive({
  categoryName: [
    { required: true, message: '请输入种类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  sortLevel: [
    { required: true, message: '请输入排序等级', trigger: 'blur' },
    { type: 'number', message: '请输入数字值', trigger: 'blur' }
  ]
});

const fetchCategories = async () => {
  loading.value = true;
  try {
    const requestData = {
      categoryName: searchName.value,
      page: currentPage.value,
      pageSize: pageSize.value
    };
    const response = await axiosInstance.post('/category/list', requestData);
    if (response.data.code === '200') {
      categories.value = response.data.data.listData;
      total.value = Number(response.data.data.total);
    }
    else {
      ElMessageBox.alert(response.data.message, '提示', {
        confirmButtonText: '确定',
        type: 'error',
        customClass: 'center-message-box'
      });
    }
  } catch (error) {
    if(error.response){
      const { status } = error.response;
      if (status === 401) {
        return;
      }
    }
    console.error(error);
    ElMessageBox.alert('获取种类列表失败，请稍后重试', '提示', {
      confirmButtonText: '确定',
      type: 'error',
      customClass: 'center-message-box'
    });
  } finally {
    loading.value = false;
  }
};

const showAddConfirm = async () => {
  try {
    // 验证表单
    await addFormRef.value.validate();
    
    await ElMessageBox.confirm(
        `确认添加种类：名称为 ${addForm.value.categoryName}，排序等级为 ${addForm.value.sortLevel}`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'question',
          customClass: 'center-message-box'
        }
    );
    await saveCategory();
  } catch (error) {
    if (error === 'cancel' || error === false) {
      return;
    }
    console.error('添加确认操作出错:', error);
    ElMessageBox.alert('添加确认操作出错，请稍后重试', '提示', {
      confirmButtonText: '确定',
      type: 'error',
      customClass: 'center-message-box'
    });
  }
};

const saveCategory = async () => {
  try {
    const response = await axiosInstance.post('/category/update', addForm.value);
    if (response.data.code === '200') {
      ElMessageBox.alert('添加成功', '提示', {
        confirmButtonText: '确定',
        type: 'success',
        customClass: 'center-message-box'
      }).then(() => {
        if (addFormRef.value) {
          addFormRef.value.resetFields();
        }
        addDialogVisible.value = false;
        fetchCategories();
      });
    } else {
      ElMessageBox.alert(response.data.message, '提示', {
        confirmButtonText: '确定',
        type: 'error',
        customClass: 'center-message-box'
      });
    }
  } catch (error) {
    console.error(error);
    ElMessageBox.alert('添加失败，请稍后重试', '提示', {
      confirmButtonText: '确定',
      type: 'error',
      customClass: 'center-message-box'
    });
  }
};

const editCategory = (category) => {
  editDialogVisible.value = true;
  editForm.value = {...category};
};

const showUpdateConfirm = async () => {
  try {
    // 验证表单
    await editFormRef.value.validate();
    
    await ElMessageBox.confirm(
        `确认修改种类：名称为 ${editForm.value.categoryName}，排序等级为 ${editForm.value.sortLevel}`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'question',
          customClass: 'center-message-box'
        }
    );
    await updateCategory();
  } catch (error) {
    if (error === 'cancel' || error === false) {
      return;
    }
    console.error('修改确认操作出错:', error);
    ElMessageBox.alert('修改确认操作出错，请稍后重试', '提示', {
      confirmButtonText: '确定',
      type: 'error',
      customClass: 'center-message-box'
    });
  }
};

const updateCategory = async () => {
  try {
    const response = await axiosInstance.post('/category/update', editForm.value);
    if (response.data.code === '200') {
      ElMessageBox.alert('修改成功', '提示', {
        confirmButtonText: '确定',
        type: 'success',
        customClass: 'center-message-box'
      }).then(() => {
        if (editFormRef.value) {
          editFormRef.value.resetFields();
        }
        editDialogVisible.value = false;
        fetchCategories();
      });
    } else {
      ElMessageBox.alert(response.data.message, '提示', {
        confirmButtonText: '确定',
        type: 'error',
        customClass: 'center-message-box'
      });
    }
  } catch (error) {
    console.error(error);
    ElMessageBox.alert('修改失败，请稍后重试', '提示', {
      confirmButtonText: '确定',
      type: 'error',
      customClass: 'center-message-box'
    });
  }
};

const showDeleteConfirm = async (categoryId) => {
  try {
    await ElMessageBox.confirm(
        '此操作将永久删除该种类, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          customClass: 'center-message-box'
        }
    );
    const response = await axiosInstance.delete(`/category/delete/${categoryId}`);
    if (response.data.code === '200') {
      ElMessageBox.alert('删除成功', '提示', {
        confirmButtonText: '确定',
        type: 'success',
        customClass: 'center-message-box'
      });
      fetchCategories();
    } else {
      ElMessageBox.alert(response.data.message, '提示', {
        confirmButtonText: '确定',
        type: 'error',
        customClass: 'center-message-box'
      });
    }
  } catch (error) {
    if (error === 'cancel') {
      return;
    }
    console.error('删除操作出错:', error);
    ElMessageBox.alert('删除操作出错，请稍后重试', '提示', {
      confirmButtonText: '确定',
      type: 'error',
      customClass: 'center-message-box'
    });
  }
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchCategories();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchCategories();
};

// 关闭添加对话框
const handleCloseAddDialog = () => {
  ElMessageBox.alert('取消更改或者添加', '提示', {
    confirmButtonText: '确定',
    type: 'info',
    customClass: 'center-message-box'
  }).then(() => {
    if (addFormRef.value) {
      addFormRef.value.resetFields();
    }
    addDialogVisible.value = false;
  });
};

// 关闭编辑对话框
const handleCloseEditDialog = () => {
  ElMessageBox.alert('取消更改或者添加', '提示', {
    confirmButtonText: '确定',
    type: 'info',
    customClass: 'center-message-box'
  }).then(() => {
    if (editFormRef.value) {
      editFormRef.value.resetFields();
    }
    editDialogVisible.value = false;
  });
};

// 初始加载数据
fetchCategories();
</script>

<style scoped>
.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.mb-4 {
  margin-bottom: 1rem;
}

.flex-1 {
  flex: 1;
}

.mr-4 {
  margin-right: 1rem;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

/* 表格头部样式 */
.table-header {
  background-color: #f5f7fa;
  color: #409EFF;
}

/* 让消息框居中的样式 */
.center-message-box .el-message-box {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

/* 动画效果 */
.el-button {
  transition: all 0.3s ease;
}

.el-table {
  transition: box-shadow 0.3s ease;
}

.el-card {
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.el-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 自定义输入框样式 - 去除黑色边框 */
:deep(.custom-input .el-input__wrapper) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: border-color 0.3s;
}

:deep(.custom-input .el-input__wrapper:hover) {
  border-color: #c0c4cc;
}

:deep(.custom-input .el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 自定义表格样式 - 优化边框 */
:deep(.custom-table .el-table__inner-wrapper) {
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

:deep(.custom-table .el-table__cell) {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

:deep(.custom-table .el-table__row:last-child .el-table__cell) {
  border-bottom: none;
}

:deep(.custom-table .el-table__cell:last-child) {
  border-right: none;
}

/* 自定义分页样式 - 优化边框 */
:deep(.custom-pagination .el-pagination__total),
:deep(.custom-pagination .el-pagination__sizes),
:deep(.custom-pagination .el-pagination__jump) {
  color: #606266;
}

:deep(.custom-pagination .el-pagination__btn),
:deep(.custom-pagination .el-pagination__sizes .el-input__wrapper) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s;
}

:deep(.custom-pagination .el-pagination__btn:hover) {
  border-color: #409eff;
  color: #409eff;
}

:deep(.custom-pagination .el-pagination__btn--active) {
  background-color: #409eff;
  border-color: #409eff;
  color: #fff;
}

/* 优化表格行悬停效果 */
:deep(.custom-table .el-table__row:hover > td.el-table__cell) {
  background-color: #f0f7ff !important;
}
</style>